package httpService

import (
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"net/http"
	"pm/config"
	"pm/db"
	"pm/model"
	"strings"
	"time"
)

const DefaultPort = "7706"

type httpService struct {
	 router *echo.Echo
}



func NewHttpService(){
    e := echo.New()
	//e.Pre(middleware.HTTPSRedirect())
	e.Pre(middleware.CORS())
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Use(checkLogin())
	e.Static("/www", "/usr/local/pm/www")
	//e.Use(middleware.Static("/usr/local/pm/www"))
    hs := new(httpService)
    hs.router = e
    hs.RegisterRouter()
    port := DefaultPort
    if config.ConfigData.HttpPort != ""{
		port = config.ConfigData.HttpPort
	}
	e.Logger.Fatal(e.Start(":" + port))
}

func checkLogin() echo.MiddlewareFunc{
	return func(next echo.HandlerFunc) echo.HandlerFunc{
		return func(c echo.Context) error {
			if config.ConfigData.HttpClose == 1{
				c.String(http.StatusNotFound, "")
				return nil
			}
			if !strings.Contains(c.Request().URL.String(), "login") && c.Request().Method == http.MethodPost{
                	token := c.Request().Header.Get("token")
                	if token == ""{
						c.String(http.StatusUnauthorized, "No access")
						return nil
					}
					var userToken model.UserToken
					if err := db.NewDb().Model(&model.UserToken{}).Where("token =?", token).Take(&userToken).Error;err != nil{
						c.String(http.StatusUnauthorized, "No access")
						return nil
					}
					if int64(userToken.EffectiveTime) < time.Now().Unix(){
						c.String(http.StatusUnauthorized, "No access timeout")
						return nil
					}
					//顺延有效时间
					userToken.EffectiveTime = int(time.Now().Add(12 * time.Hour).Unix())
					db.NewDb().Save(userToken)
				c.Set("login_user", userToken.Name)
			}
			return next(c)
		}
	}
}